<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="title" :width="650" destroyOnClose showFooter>
    <BasicForm @register="registerForm" >
      <template #name="{ model, field, schema }">
        <a-input v-bind="schema.componentProps" v-model:value="model[field]" @change="handlePackageNameChange"/>
      </template>
    </BasicForm>
    <BasicTree
      ref="treeRef"
      checkable
      toolbar
      :treeData="treeData"
      :checkedKeys="checkedKeys"
      :expandedKeys="allTreeKeys"
      :selectedKeys="selectedKeys"
      :checkStrictly="true"
      :clickRowToExpand="true"
      search
      title="所拥有的功能"
      @check="onCheck"
    >
      <template #title="{ title, ruleFlag, perms }">
        <span>{{ title }} </span>
        <span style="padding-left: 5px">{{ perms.split(',').join(' | ') }}</span>
        <Icon v-if="ruleFlag" icon="ant-design:align-left-outlined" style="margin-left: 5px; color: red" />
      </template>
    </BasicTree>

    <!--右下角按钮-->
    <template #footer>
      <PopConfirmButton title="确定放弃编辑？" @confirm="closeDrawer" okText="确定" cancelText="取消">取消</PopConfirmButton>
      <a-button @click="handleSubmit(false)" type="primary" :loading="loading" ghost style="margin-right: 0.8rem">仅保存</a-button>
      <a-button @click="handleSubmit(true)" type="primary" :loading="loading">保存并关闭</a-button>
    </template>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from "vue"
  import { BasicDrawer, useDrawer, useDrawerInner } from "/@/components/Drawer"
  import { BasicTree, TreeItem } from "/@/components/Tree"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { PopConfirmButton } from "/@/components/Button"
  import { saveOrUpdateTenantPackage } from "./api"
  import { formPermissionSchema } from "./data"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { Icon } from "/@/components/Icon"
  import { useUserStore } from "/@/store/modules/user"
  import { eachTree } from "/@/utils/helper/treeHelper"
  import { TenantType } from "/@/enums/bizEnum"
  const packageName = ref()

  const userStore = useUserStore()

  const { createMessage } = useMessage()
  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 80,
    labelCol: {
      md: { span: 4 },
      sm: { span: 6 },
    },
    wrapperCol: {
      md: { span: 20 },
      sm: { span: 18 },
    },
    schemas: formPermissionSchema,
    showActionButtonGroup: false,
  })
  // 声明Emits
  const emit = defineEmits(["success", "register"])
  //树的信息
  const treeData = ref<TreeItem[]>([])
  //树的全部节点信息
  const allTreeKeys = ref<any>([])
  //树的选择节点信息
  const checkedKeys = ref([])
  const defaultCheckedKeys = ref([])
  //树的选中的节点信息
  const selectedKeys = ref([])
  const sceneId = ref("")

  //树的实例
  const treeRef = ref(null)
  const loading = ref(false)

  const isUpdate = ref(true)
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await reset()
    setDrawerProps({ confirmLoading: false, loading: true })
    isUpdate.value = !!data?.isUpdate
    const menuIds = data?.record?.menuIds || []

    if (unref(isUpdate)) {
      //表单赋值
      await setFieldsValue({ ...data.record })
    }

    packageName.value = data.record?.name

    if (userStore.getSelectTenant.tenantType != TenantType.MANAGE || userStore.getIsSysAdminTenant) {
      updateSchema({
        field: "sceneId",
        component: "ApiSelect",
        componentProps: {
          optionFilterProp: "label",
          labelField: "name",
          valueField: "id",
          showSearch: true,
          // api: listScene,
          onSelect: async (value: any, option: any) => {
            console.log("option", option)

            sceneId.value = value
            setDrawerProps({ confirmLoading: false, loading: true })
            // listPermissionTree({ sceneId: sceneId.value })
            //   .then((roleResult) => {
            //     treeData.value = roleResult.treeList
            //     allTreeKeys.value = roleResult.menuList.map((e) => e.id)
            //   }).finally(() => {
            //     setDrawerProps({ loading: false })
            //   })
          },
          onOptionsChange: async (options) => {
            if (options && options.length > 0) {
              sceneId.value = data?.record?.sceneId || options[0].value
              setFieldsValue({ sceneId: sceneId.value })
              // const roleResult = await listPermissionTree({ sceneId: sceneId.value })
              // treeData.value = roleResult.treeList
              // allTreeKeys.value = roleResult.menuList.map((e) => e.id)
              // setDrawerProps({ loading: false })
            }
          },
        },
      })
    } else {
      listPermissionTree({ sceneId: userStore.getSelectTenant.sceneId, allSceneMenu: true })
        .then((roleResult) => {
          treeData.value = roleResult.treeList
          allTreeKeys.value = roleResult.menuList.map((e) => e.id)
        }).finally(() => {
          setDrawerProps({ loading: false })
        })
    }

    // 初始化菜单数据
    checkedKeys.value = menuIds
    defaultCheckedKeys.value = menuIds
  })

  const title = computed(() => {
    return packageName.value ? `套餐权限配置【${packageName.value}】` : '套餐权限配置'
  })

  const handlePackageNameChange = (e) => {
    packageName.value = e.target.value
    setDrawerProps({ title })
  }

  /**
   * 点击选中
   */
  function onCheck(o) {
    checkedKeys.value = o.checked ? o.checked : o
  }

  /**
   * 数据重置
   */
  function reset() {
    treeData.value = []
    allTreeKeys.value = []
    checkedKeys.value = []
    defaultCheckedKeys.value = []
    selectedKeys.value = []
    resetFields()
  }
  /**
   * 获取tree实例
   */
  function getTree() {
    const tree = unref(treeRef)
    if (!tree) {
      throw new Error("tree is null!")
    }
    return tree
  }
  /**
   * 提交
   */
  async function handleSubmit(exit) {
    try {
      let values = await validate()
      let params = {
        // @ts-ignore
        menuIds: getTree().getCheckedKeys(),
        lastMenuIds: defaultCheckedKeys.value,
      }
      const from = { sceneId: userStore.getSelectTenant.sceneId, ...values, ...params }
      console.log("from", from)

      loading.value = true
      await saveOrUpdateTenantPackage(from, unref(isUpdate))
      exit && closeDrawer()
      emit("success")
      createMessage.success("操作成功")
    } finally {
      loading.value = false
    }
  }
</script>
